<?php
namespace Api\Controller;

class CommentController extends APIController {
    public $tbName = CONTROLLER_NAME;

    /*待验证的参数*/
    public $tca = [
        'goods_id' => [
            'method' => 'exists',
            'model' => 'Goods',
            'code_key' => 'lawless'
        ],
        'user_id' => [
            'method' => 'exists',
            'model' => 'member',
            'code_key' => 'lawless'
        ],
        'order_id' => [
            'method' => 'exists',
            'model' => 'Order',
            'code_key' => 'lawless'
        ],
        'content' => [
            'method' => 'regex',
            'model' => '/\S/',
            'code_key' => 'content_missing'
        ],
        'service_level' => [
            'method' => 'regex',
            'model' => '/^[1-5]$/',
            'code_key' => 'lawless'
        ],
        'product_level' => [
            'method' => 'regex',
            'model' => '/^[1-5]$/',
            'code_key' => 'lawless'
        ],
        'postage_level' => [
            'method' => 'regex',
            'model' => '/^[1-5]$/',
            'code_key' => 'lawless'
        ]
    ];
    /*保存参数*/
    public $field = ['user_id','order_id','goods_id','content','service_level','product_level','postage_level','is_has_attach'];

    /**
     * 列表页面-商品评价
     */
    public function index() {
        try{
            $this->safeChecked();
            /*验证*/
            $this->tca = array('goods_id' => array('method' => 'exists','model' => 'Goods','code_key' => 'lawless'));
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $Obj = D($this->tbName); //实例化对象
            $goods_id = I('param.goods_id',0);
            $has_attach = I('param.has_attach',0);
            $where['a.goods_id'] = $goods_id;
            if($has_attach){
                $where['a.is_has_attach'] = 1;
            }
            $list = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                    ->join(C('DB_PREFIX').'order as c on a.order_id = c.id')
                    ->where($where)
                    ->Field('a.id,a.content,a.reply,a.crdate,b.wxlogo,b.nickname,c.assistant')
                    ->order('a.crdate desc')
                    ->limit(($page -1)*$show_num,$show_num)
                    ->select();
            if($list){
                $Attach = M('attach');
                foreach ($list as $key => &$value) {
                    $value['crdate'] = date('Y-m-d',$value['crdate']);
                    $attch_info = [
                        'info_id' => $value['id'],
                        'info_tab' =>  $this->tbName
                    ];
                    /*附件*/
                    $attach = $Attach->where($attch_info)->Field('crdate,path')->select();
                    $value['attach'] = array();
                    if($attach){
                        foreach ($attach as $k => $v) {
                           $value['attach'][] = C('DOMAIN_URL').C('PATH_UPLOAD').$this->tbName.'/'.date('Ym',$v['crdate']).'/'.$v['path'];
                        }
                    }       
                }
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 列表页面-我的评价
     */
    public function list() {
        try{
            $this->safeChecked();
            /*验证*/
            $this->tca = array('user_id' => array('method' => 'exists','model' => 'Member','code_key' => 'lawless'));
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $user_id = I('param.user_id');
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $where['a.user_id'] = $user_id;
            $Obj = M($this->tbName);
            $list = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'order as c ON a.order_id = c.id')
                    ->join(C('DB_PREFIX').'goods as d ON a.goods_id = d.id')
                    ->where($where)
                    ->Field('a.id,a.content,a.reply,a.crdate,a.service_level,a.product_level,a.postage_level,c.deal_money,c.goods_name,c.assistant,d.image,d.crdate as createtime')
                    ->order('a.crdate desc')
                    ->limit(($page -1)*$show_num,$show_num)
                    ->select();
            if($list){
                $Attach = M('attach');
                foreach ($list as $key => &$value) {
                    $value['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$value['createtime']).'/'.$value['image'];
                    $value['crdate'] = date('Y-m-d H:i:s',$value['crdate']);
                    $attch_info = [
                        'info_id' => $value['id'],
                        'info_tab' =>  $this->tbName
                    ];
                    /*附件*/
                    $attach = $Attach->where($attch_info)->Field('crdate,path')->select();
                    $value['attach'] = array();
                    if($attach){
                        foreach ($attach as $k => $v) {
                           $value['attach'][] = C('DOMAIN_URL').C('PATH_UPLOAD').$this->tbName.'/'.date('Ym',$v['crdate']).'/'.$v['path'];
                        }
                    }       
                }
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     *	评价
     */
    public function comment(){
    	try{
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $data = I('param.');
            $Obj = D($this->tbName);
            $Order = D('Order');
            $count = $Obj->where(array('order_id' => $data['order_id']))->select();
            if($count){
                $this->res_data['code_key'] = 'order_commented';
                $this->apiReply();
            }
            $order_info = $Order->Field('status')->find($data['order_id']);
            if($order_info['status'] != 4){
                $this->res_data['code_key'] = 'order_status_error';
                $this->apiReply();
            }
            $Obj->startTrans();
            //数据保存
            $param = $data;
            $this->filterCoupon($data);
            $data['crdate'] = $data['tstamp'] = time();
            $id = $Obj->add($data);
            if(!$id){
                debug($Obj->_sql());
                $Obj->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            if($param['file']){
                $param['file'] = json_decode($param['file'],true);
                $Attach = M('attach');
                /*添加附件记录*/
                foreach ($param['file'] as $key => $value) {
                    $file_info = array(
                        'tstamp' => time(),
                        'crdate' => time(),
                        'info_id' => $id,
                        'info_tab' => $this->tbName,
                        'path' => $value,
                    );
                    $flag = $Attach->add($file_info);
                    if(!$flag){
                        debug($Attach->_sql());
                        $Obj->rollback();
                        $this->res_data['code_key'] = 'fail';
                        $this->apiReply();
                    }
                }
            }
            //修改订单状态
            $status = $Order->where(array('id' => $data['order_id']))->save(array('status' => 5,'tstamp' => time()));
            if(!$status){
                debug($Order->_sql());
                $Obj->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            $Obj->commit();
    	}catch(\Exception $e){
    		debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
    	}
        $this->apiReply();
    }

    /**
     * 文件上传
     * @param $key           上传字段名
     * @param $path          上传主路径('/'结尾)
     * @param $save_path     主路径下的文件夹('/'结尾)
     * @param $extent_path   扩展文件夹('/'结尾)
     * @param $type         文件类型限制
     */
    public function uploadFiles() {
        import('Org.Net.UploadFile');// 导入类
        $upload = new \Org\Net\UploadFile(); // 实例化上传类
        $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg'); //设置附件上传类型
        $upload->maxSize = 1024*1000*1000*20; // 设置附件上传大小20M
        $upload->savePath = C('PATH_UPLOAD').$this->tbName.'/'.date('Ym').'/'; // 设置附件上传目录
        $upload->uploadReplace = false; //存在同名是否覆盖
        $upload->saveRule = 'uniqid'; //上传文件命名规则, 没有定义命名规则，则保持文件名不变

        $result = array();
        if ($upload->upload('image')) { // 上传错误提示错误信息
            $rs = $upload->getUploadFileInfo();
            $this->res_data['data'] = $rs[0]['savename'];
        } else { // 上传成功 获取上传文件信息
            debug($upload->getErrorMsg());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /*数据筛选*/
    public function filterCoupon(&$data){
        foreach ($data as $key => $value) {
            if(!in_array($key,$this->field)){
                unset($data[$key]);
            }
        }
    }
}

?>